//
//  StartViewController.m
//  DriverBus
//
//  Created by MacMini20170218 on 2017/3/27.
//  Copyright © 2017年 JiYang. All rights reserved.
//

#import "StartViewController.h"
#import "AppDelegate.h"
#import "NetWorking.h"
#import "JRToast.h"
#import "Bus.h"
#import "BusStop.h"

@interface StartViewController ()

@end

@implementation StartViewController{
    NSMutableArray * buses;
    UIAlertView *alert;
    AppDelegate *app;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    app = (AppDelegate*)[[UIApplication sharedApplication]delegate];
    app.direction = -1;
    app.hasConnectServer = NO;
    //设置界面控件
    [self.driverNameLabel setText:[NSString stringWithFormat:@"%@师傅，你好",app.driver.name]];
    
    
    alert = [[UIAlertView alloc]init];
    [alert setTitle:@"选择你的车型:"];
    [alert setDelegate:self];
    [self.selecDirectuibSwitch addTarget:self action:@selector(switchDirection:) forControlEvents:UIControlEventValueChanged];
    if(![NetWorking netConnect]){
        UIAlertView *alertNet = [[UIAlertView alloc]initWithTitle:@"网络错误" message:@"网络未连接，请检查网络连接." delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        alertNet.alertViewStyle = UIAlertViewStyleDefault;
        [alertNet show];
        return;
    }
    [self.loadingView setHidden:NO];
    [self getDriverInfo];
    [self getBusStops];
}

//方向选择的监听
- (void)switchDirection:(UISegmentedControl *)seg{
    switch (seg.selectedSegmentIndex) {
        case 0:
            //后门方向
            app.direction = 1;
            break;
        case 1:
            //16栋方向
            app.direction =2;
            break;
    }
}

- (IBAction)clickGoButton:(id)sender {
    if(![NetWorking netConnect]){
        UIAlertView *alertNet = [[UIAlertView alloc]initWithTitle:@"网络错误" message:@"网络未连接，请检查网络连接." delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        alertNet.alertViewStyle = UIAlertViewStyleDefault;
        [alertNet show];
        return;
    }
    if(app.direction==-1){
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"方向未选择" message:@"请先选择你的目的方向" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
        return;
    }
    if(app.busStopsDictionary.count<1){
        [JRToast showWithText:@"获取站点信息中"];
        [self getBusStops];
        return;
    }
    //跳转到主界面
    [self performSegueWithIdentifier:@"MainViewSegue" sender:self];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if([segue.identifier isEqualToString:@"MainViewSegue"]){
        UINavigationController *nav = (UINavigationController*)segue.destinationViewController;
        MainViewController *mainViewController = (MainViewController*)nav.topViewController;
        mainViewController.delegate = self;
    }else if([segue.identifier isEqualToString:@"UserCenterSegue"]){
        UserCenterController *userCenter = (UserCenterController*)segue.destinationViewController;
        userCenter.delegate = self;
    }
}

#pragma mark 获取个人信息
- (void)getDriverInfo{
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    [dict setObject:app.driver.account forKey:@"dri_account"];
    [dict setObject:app.driver.pass forKey:@"dri_password"];
    NSString * loginUrl = @"http://122.114.61.173/bus/index.php/Home/DriLogin/login";
    AFHTTPSessionManager *manage = [NetWorking manager];
    [manage POST:loginUrl parameters:dict
        progress:^(NSProgress * _Nonnull uploadProgress) {
        }
         success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
             [self.loadingView setHidden:YES];
             if(responseObject){
                 NSDictionary* result = responseObject;
                 NSString* status = [result objectForKey:@"login_code"];
                 AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];
                 if([status isEqualToString:@"1"]){
                     //登录成功
                     appDelegate.driver.name = [result objectForKey:@"dri_name"];
                     appDelegate.driver.number = [result objectForKey:@"jub_num"];
                     appDelegate.driver.sex = [result objectForKey:@"dri_sex"];
                     appDelegate.driver.imageUrl = [result objectForKey:@"head_address"];
                     //保存已经登录和用户信息
                     [appDelegate.driver saveToData:YES];
                     //设置到界面
                     [self.driverNameLabel setText:[NSString stringWithFormat:@"%@师傅，你好",app.driver.name]];
                     [self loadDriverImage];
                 }else{
                     //登录失败
                     [JRToast showWithText:@"登录失败，请重试"];
                     [appDelegate.driver saveToData:NO];
                 }
             }
         }
         failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
             [self.loadingView setHidden:YES];
             if(error){
                 NSLog(@"发车界面登录出错:%@",error);
             }
         }];
    
}

#pragma mark 加载图片
- (void)loadDriverImage{
    [self.imageLoading startAnimating];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURL *url = [NSURL URLWithString:app.driver.imageUrl];
    NSURLSessionTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        [self.imageLoading stopAnimating];
        if(error==nil){
            UIImage *image = [UIImage imageWithData:data];
            if(image){
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.imageView.image = image;
                    //以下两行设置圆角
                    self.imageView.layer.cornerRadius = 10;
                    //将多余的部分切掉
                    self.imageView.layer.masksToBounds = YES;
                });
            }
        }else{
            NSLog(@"下载图片错误:%@",error);
        }
    }];
    [task resume];
}

#pragma mark 获取站点
- (void)getBusStops{
    if(app.busStopsDictionary.count > 1){
        return;
    }
    if([self.loadingView isHidden]){
        [self.loadingView setHidden:NO];
    }
    NSString *getBusStopsUrl = @"http://122.114.61.173/bus/index.php/Home/BusStop/getBusStopInformation";
    AFHTTPSessionManager *manager2 = [NetWorking manager];
    [manager2 POST:getBusStopsUrl parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self.loadingView setHidden:YES];
        NSString *status = [responseObject objectForKey:@"status_code"];
        if([status isEqualToString:@"1"]){
            NSMutableDictionary *dict= [responseObject objectForKey:@"data"];
            app.busStopsDictionary = [[NSMutableDictionary alloc]init];
            for(NSMutableDictionary *d in dict){
                BusStop *stop = [[BusStop alloc]init];
                stop.stopId = [d objectForKey:STOP_ID];
                stop.name = [d objectForKey:STOP_NAME];
                stop.longitude = [d objectForKey:STOP_LOG];
                stop.latitude = [d objectForKey:STOP_LAT];
                [app.busStopsDictionary setObject:stop forKey:stop.stopId];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self.loadingView setHidden:YES];
        [JRToast showWithText:@"获取站点信息失败"];
    }];
    
}

//点击了主界面的到达按钮,复原发车界面数据
- (void)terminal{
    app.direction = -1;
    [self.selecDirectuibSwitch setSelectedSegmentIndex:-1];
}

- (void)exitLog{
    NSLog(@"exit log");
    [self performSegueWithIdentifier:@"ExitLogSegue" sender:nil];
}

@end
